<?php
	session_start();
	//引入公共文件
	require('../common/common.php');
	//实例化Model对象
	$model = new Model('bbs_user');
	
	//接收信息 并去掉传值两侧的空白
	$_POST['username'] = trim(isset($_POST['username']) ? $_POST['username'] : '');
	$_POST['password'] = trim(isset($_POST['password']) ? $_POST['password'] : '');
	$_POST['password2'] = trim(isset($_POST['password2']) ? $_POST['password2'] : '');
	$_POST['email'] = trim(isset($_POST['email']) ? $_POST['email'] : '');	
	//判断用户名密码是否为空
	if(empty($_POST['username']) || empty($_POST['password'])) {
		echo "<script>alert('用户名或密码不能为空!');window.history.back(-1);</script>";
		return;
	}

	
	//判断type信息进行处理
	switch ($_GET['type']) {
		case 'add':
			//判断两次输入的密码
			if($_POST['password'] != $_POST['password2']) {
				echo "<script>alert('两次密码不一致，请重新输入！');window.history.back(-1);</script>";
				return;
			} else {
	
				$_POST['password'] = md5($_POST['password']);
			}
			
			//判断用户是否被注册
			$name = isset($_POST['username']) ? $_POST['username'] : '';
			$sqlfree1 = "SELECT `username` FROM `bbs_user` WHERE username = '{$name}' ";
			$row = $model->free($sqlfree1);
			if($row) {
				echo "<script>alert('该用户名已被注册！');window.history.back(-1);</script>";
				return;
			}
			
			//验证邮箱
			$email = $_POST['email'];
			if($email != (strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email))) {
				echo "<script>alert('邮箱格式不正确！');window.history.back(-1);</script>";
				return;
			}
			//判断验证码
			if(empty($_POST['code'])){
				echo "<script>alert('请输入验证码！');window.history.back(-1);</script>";
				return;
			} else {
				if($_POST['code'] != $_SESSION['code']) {
					echo "<script>alert('验证码输入错误！');window.history.back(-1);</script>";
					return;
				}
			}
			
			//执行添加
			$res = $model->insert();
			if($res > 0) {
				$_SESSION['username'] = $_POST['username'];
				echo "<script>
						alert('注册成功');
						window.location.href='../index.php';
					</script>";
			} else {
				echo "<script>alert('添加失败！');window.history.back(-1);</script>";
				return;
			}
			
			break;
		
		default:
			//没有值跳回首页
			echo "<script>
						window.location.href='../index.php';
				</script>";
			break;
	}
 ?>